package com.ubhave.powertrackernof1;

import java.util.Date;

import com.ubhave.powertrackernof1.R;

//import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class DailyGoalUpdateFeedbackActivity extends FragmentActivity implements LoginDialogListener{
        
    String[] feedbackGood;
	String[] feedbackOK;
	String[] feedbackBad;
	String[] feedbackGoodAlt;
	String[] feedbackOKAlt;
	String[] feedbackBadAlt;
	Bundle bundle;
	int score;
	int count;
	int day;
	int feedbackDay;
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	
	Resources res;
	
	String usr;
	String intervention;
	
	LifeGuideConnector lgc;
	PageSensorLogger psl;
	PageLogger pl;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dailygoalupdatefeedback);
        
        res = getResources();
        bundle = getIntent().getExtras();
        
        feedbackGood = res.getStringArray(R.array.dailygoalfeedbackgood);
        feedbackOK = res.getStringArray(R.array.dailygoalfeedbackok);
        feedbackBad = res.getStringArray(R.array.dailygoalfeedbackbad);
        
        feedbackGoodAlt = res.getStringArray(R.array.dailygoalfeedbackgoodalt);
        feedbackOKAlt = res.getStringArray(R.array.dailygoalfeedbackokalt);
        feedbackBadAlt = res.getStringArray(R.array.dailygoalfeedbackbadalt);
        
        score=0;
        count=0;
        day=1;
        
        settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        editor = settings.edit();
        
        usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
		lgc = new LifeGuideConnector(settings);
        
		if(settings.getBoolean("SensorsOn", false))
			psl = new PageSensorLogger(this);
		pl=new PageLogger(this);
		
		class AsyncLogAndRetrieve extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				//Usage Logging
				try{
					/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+" "+new Date()+", ");
		        	editor.commit();
		        	if(!usr.equals("")&&!intervention.equals(""))
		        		lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
		        	else
		        		Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);
		        	*/
					pl.makeLog();
		        	//Sensor Logging
		        	if(settings.getBoolean("SensorsOn", false)){
		    			psl.makeLog();
		        	}
				}
				catch(PowerTrackerInvalidAuthKeyException e){
					invalidKey();					
				}
				return null;
			}
		};
		new AsyncLogAndRetrieve().execute(this);

        String[] startDateString = settings.getString("appStart", "").split("-");
		Date startDate = new Date(new Integer(startDateString[2]),new Integer(startDateString[1]),new Integer(startDateString[0]));
		Date currentDate = new Date();
		long diff = currentDate.getTime()-startDate.getTime();
		double daysDiff = diff/(1000*60*60*24);
		day=1+new Double(Math.floor(daysDiff)).intValue();
        
        for(int i=1;i<7;i++){
        	if(bundle.getString("dailygoalupdate"+i)!=null){
        		score+=new Integer(bundle.getString("dailygoalupdate"+i));
        		count++;
        	}
        }
        
        editor.putString("dailygoalupdate"+day, ""+Math.round(new Double(new Double(score)/new Double(count))));
		editor.commit();
        
        
        Log.i("POWeR Tracker: ", "Update Score: "+score+" "+Math.round(new Double(new Double(score)/new Double(count))));
        
        TextView feedbacktv = (TextView)findViewById(R.id.DailyGoalFeedback);
        
        feedbackDay=day;
        if(feedbackDay>7&&settings.getString("interventionMode", "").equals("1"))
        	feedbackDay=feedbackDay-7;
        
        if(feedbackDay>14)
        	feedbackDay=(feedbackDay%14);
        if(feedbackDay==0)
        	feedbackDay=14;
        
                
        
        //These If/Else stacks are a horrible way to do the conditional part of feedback. It will have to do for now but needs to be done properly eventually.
        if(Math.round(new Double(new Double(score)/new Double(count)))<=1){
        	if(feedbackDay==9&&!settings.getString("dailygoalupdate7", "").equals("1")&&!settings.getString("dailygoalupdate8", "").equals("1"))
        		feedbacktv.setText(feedbackBadAlt[feedbackDay-1]);
        	else
        		feedbacktv.setText(feedbackBad[feedbackDay-1]);
        }
        else if(Math.round(new Double(new Double(score)/new Double(count)))==2){
        	if(feedbackDay==8&&settings.getString("dailygoalupdate1", "").equals("1"))
        		feedbacktv.setText(feedbackOKAlt[feedbackDay-1]);
        	else        	
        		feedbacktv.setText(feedbackOK[feedbackDay-1]);
        }
        else if(Math.round(new Double(new Double(score)/new Double(count)))>=3){
        	if(feedbackDay==2&&settings.getString("dailygoalupdate1", "").equals("3"))
        		feedbacktv.setText(feedbackGoodAlt[feedbackDay-1]);
        	else if(feedbackDay==3&&(!settings.getString("dailygoalupdate1", "").equals("3")||!settings.getString("dailygoalupdate2", "").equals("3")))
        		feedbacktv.setText(feedbackGoodAlt[feedbackDay-1]);
        	else if(feedbackDay==8&&!settings.getString("dailygoalupdate1", "").equals("3"))
        		feedbacktv.setText(feedbackGoodAlt[feedbackDay-1]);
        	else
        		feedbacktv.setText(feedbackGood[feedbackDay-1]);
        }
 
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(psl!=null)
        	psl.resumeLocationSensing();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        	
    	switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                goHome();
                return true;
            case R.id.home:
                // app icon in options clicked; go home
            	goHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.o_menu, menu);
        return true;
    }
    
    public void goHome(){
    	Intent intent = new Intent(this, PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    public void backToMenu(View v){
    	
    	Intent myIntent = new Intent().setClass(this, PowerTrackerActivity.class);
    	startActivityForResult(myIntent, 0);
	
    }
    
    public void backToViewGoals(View v){
    	
    	Intent myIntent = new Intent().setClass(this, ViewGoalsActivity.class);
    	startActivityForResult(myIntent, 0);
	
    }
    
    public void invalidKey(){
		DialogFragment dialog = new LoginDialog();
		Bundle errorBundle = new Bundle();
	    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
	    dialog.setArguments(errorBundle);
	    //dialog.show(this.getFragmentManager(), "LoginDialog");
	    dialog.show(this.getSupportFragmentManager(), "LoginDialog");
	}
    
  	@Override
	public void onLoginDialogPositiveClick() {
		// TODO Auto-generated method stub
  		Log.i("POWeR Tracker Special: ","Clicked OK");
  		finish();
  		startActivity(getIntent());
	}


	@Override
	public void onLoginDialogNegativeClick() {
		// TODO Auto-generated method stub
		Log.i("POWeR Tracker Special: ","Clicked Cancel");
		goHome();
	}
}